#include "src/bsp/led.h"
#include "src/bsp/wifi_manager.h"
#include "src/middleware/business.h"

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#define YOUR_SSID "yourwifissid"            // wifi账号
#define YOUR_PSWD "yourwifipassword"        // wifi密码
#define YOUR_MACAddress "AA:BB:CC:DD:EE:FF" // 需要开机的MAC地址

#define BEMFA_SERVER_URL "bemfa.com" // 巴法MQTT服务器地址
#define BEMFA_SERVER_PORT 9501       // 巴法MQTT服务器端口
#define BEMFA_KEY "XXX32BITXXX"      // 巴法私钥

#define TOPIC_CONTROL "control"
#define TOPIC_FEEDBACK "feedback"

#define BTN_PIN 5 // 按键引脚号

/**** 变量声明 ****/
WifiManager gWifiManager;

/**** 函数声明 ****/
void buttonLoop();

void setup()
{
    Serial.begin(115200);

    // 外设初始化
    pinMode(BTN_PIN, INPUT);
    ledInit();

    gWifiManager.setMacAddress(YOUR_MACAddress);

    // 连接wifi
    while (!gWifiManager.setWifiConnection(YOUR_SSID, YOUR_PSWD))
    {
        Serial.print("Connecting to wifi: ");
        Serial.print(YOUR_SSID);
        Serial.print(" failed. Try again now..");
    }

    mqttClientInit(BEMFA_SERVER_URL, BEMFA_SERVER_PORT, BEMFA_KEY, TOPIC_CONTROL, TOPIC_FEEDBACK, &gWifiManager);
}

void loop()
{
    mqttClientLoop();
    buttonLoop();
}

void buttonLoop()
{
    if (digitalRead(BTN_PIN) == LOW)
    {                                    // 若按键被按下
        delay(80);                       // 消抖
        if (digitalRead(BTN_PIN) == LOW) // 若按键被按下
        {
            ledAlwaysOn();
            gWifiManager.doWol();
            ledAlwaysOff();
        }
    }
}